﻿using System;
using System.Data.SqlClient;
using System.IO;
using Sys.Serialization;

namespace Sys.SqlServer.Smo.Connection
{
    [Serializable]
    public class ConnectionString
    {
        public string Server { get; set; }

        public string Username { get; set; }

        public string Password { get; set; }

        public string Database { get; set; }

        public bool Trusted { get; set; }

        public ConnectionString()
        {
            Server = ".";
            Username = string.Empty;
            Password = string.Empty;
            Database = "master";
            Trusted = true;
        }

        public bool TestConnection()
        {
            bool result = false;

            try
            {
                using (SqlConnection connection = new SqlConnection(ToString()))
                {
                    connection.Open();
                    connection.Close();
                }

                result = true;
            }
            catch
            {
                result = false;
            }

            return result;
        }

        public void Save(FileInfo f)
        {
            Serializer<ConnectionString>.Current.SerializeToFile(this, f);
        }

        public void Load(FileInfo f)
        {
            ConnectionString c = Serializer<ConnectionString>.Current.DeserializeFromFile(f);

            if (c != null)
            {
                Server = c.Server;
                Database = c.Database;
                Username = c.Username;
                Password = c.Password;
                Trusted = c.Trusted;
            }
        }

        public override string ToString()
        {
            string result = string.Empty;

            if (Trusted)
                result = string.Format("Server={0};Database={1};Trusted_Connection={2};", Server, Database, Trusted);
            else
                result = string.Format("Server={0};Database={1};User ID={2};Password={3};", Server, Database, Username, Password);

            return result;
        }
    }
}
